/**    
 * @{#} MyFollowingDoctorActivity.java Create on 2014-7-8 下午2:49:08    
 *          
 * @author <a href="mailto:evan0502@qq.com">Evan</a>   
 * @version 1.0    
 */
package com.smiier.skin;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import cn.o.app.event.listener.OnSelectedChangeListener;
import cn.o.app.json.JsonUtil;
import cn.o.app.net.INetTask;
import cn.o.app.net.NetTaskListener;
import cn.o.app.ui.OTab;
import cn.o.app.ui.OTabItem;
import cn.skinapp.R;

import com.evan.common.pullrefresh.PullToRefreshBase;
import com.evan.common.pullrefresh.PullToRefreshBase.OnRefreshListener;
import com.evan.common.pullrefresh.PullToRefreshListView;
import com.pifuke.adapter.SampleUserAdapter;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.net.FollowGetFollowersListTask;
import com.smiier.skin.net.FollowGetFollowersListTask.FollowGetFollowersListRequest;
import com.smiier.skin.net.FollowGetFollowersListTask.FollowGetFollowersListResponse;
import com.smiier.skin.net.FollowGetListTask;
import com.smiier.skin.net.FollowGetListTask.FollowGetListRequest;
import com.smiier.skin.net.FollowGetListTask.FollowGetListResponse;
import com.smiier.skin.net.RelationshipGetListTask;
import com.smiier.skin.net.RelationshipGetListTask.RelationshipGetListRequest;
import com.smiier.skin.net.RelationshipGetListTask.RelationshipGetListResponse;
import com.smiier.skin.net.UserGetTask;
import com.smiier.skin.net.UserGetTask.UserGetRequest;
import com.smiier.skin.net.UserGetTask.UserGetResponse;
import com.smiier.skin.net.entity.Follow;
import com.smiier.skin.net.entity.RelationShip;
import com.smiier.skin.net.entity.User;
import com.smiier.skin.net.entity.UserWrapper;
import com.smiier.skin.ui.BasicActivity;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.utils.CommonUtility;

public class MyFollowingDoctorActivity extends BasicActivity implements
		OnRefreshListener<ListView>, OnItemClickListener {

	private PullToRefreshListView list_following_doctor;
	// private TextView text_empty;
	HashMap<String, Object> params = new HashMap<String, Object>(),
			params_ = new HashMap<String, Object>();
	private ArrayList<Object> array = new ArrayList<Object>();
	private Long mStartUid;
	private int targetType;
	private boolean mMyFollowDoctor = false;
	private OTab mTab;
	private int mPos;
	private SampleUserAdapter mMyAdapter;
	private final static String mFollow = "我关注的(%s)";
	private final static String mFollowed = "关注我的(%s)";
	private OTabItem mMyFollow;
	private OTabItem mFollowMe;
	private boolean mShowTitleNumberFollow = true;
	private boolean mShowTitleNumberFollowed = true;
	private OTab mMyTab;
	RelationshipGetListRequest req = new RelationshipGetListRequest();
	ArrayList<UserWrapper> Users = new ArrayList<UserWrapper>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_myfollowing_doctor);
		mMyFollowDoctor = getIntent().getBooleanExtra(Constant.mFollowDoctor,
				false);
		init();
		// text_empty = (TextView) findViewById(R.id.text_empty);
		mTab = findViewById(R.id.tab, OTab.class);
		mMyTab = findViewById(R.id.tab_my_doctor, OTab.class);
		mMyFollow = findViewById(R.id.my_follow, OTabItem.class);
		mFollowMe = findViewById(R.id.follow_me, OTabItem.class);
		targetType = 2;
		mMyAdapter = new SampleUserAdapter();
		if (mMyFollowDoctor) {
			mTab.setVisibility(View.VISIBLE);
			setNavTitle("我关注的医生");
			// text_empty.setText("您还没有关注的医生");
			mPos = 1;
			loadData(false);
			mPos = 0;
			loadData(false);
		} else {
			mMyTab.setVisibility(View.VISIBLE);
			mTab.setVisibility(View.GONE);
			setNavTitle("我的医生");
			// text_empty.setText("您还没有与您建立关系的医生");
			targetType = 1;
			mPos = 2;
		}
		setNavLeftBtn("我的");

		if (!mMyFollowDoctor) {
			// setNavRightBtn("+");
		}
		text_right.setTextSize(35);

		list_following_doctor = (PullToRefreshListView) findViewById(R.id.list_myfollowing);
		list_following_doctor.setOnRefreshListener(this);
		list_following_doctor.setPullRefreshEnabled(false);
		list_following_doctor.setScrollLoadEnabled(true);
		ListView list = list_following_doctor.getListView();
		// list.setEmptyView(text_empty);
		params.put(Constant.PARAM_API, "Follow.GetList");
		params.put("pageSize", Constant.pageSize);
		params.put("User_Type", 2);
		params.put(Constant.PARAM_TOKEN, GlobalSettings.sToken);

		params_.put(Constant.PARAM_API, "User.Get");

		list_following_doctor.setOnItemClickListener(this);
		list_following_doctor.setAdapter(mMyAdapter);
		mMyTab.setOnSelectedChangeListener(new OnSelectedChangeListener() {

			@Override
			public void onChanged(View v, int index) {
				//
				Users.clear();
				if (index == 0) {
					req.RSSource = null;
				} else if (index == 1) {
					req.RSSource = RelationShip.SOURCE_SAOMIAO;
				} else if (index == 2) {
					req.RSSource = RelationShip.SOURCE_ONLINE;
				} else if (index == 3) {
					req.RSSource = RelationShip.SOURCE_GENZONG;
				}
				mMyAdapter.setDataProvider(null);
				mMyAdapter.notifyDataSetChanged();
				// loadData(false);
				onPullDownToRefresh(null);
			}
		});
		mTab.setOnSelectedChangeListener(new OnSelectedChangeListener() {

			@Override
			public void onChanged(View v, int index) {
				mMyAdapter.setDataProvider(null);
				mMyAdapter.notifyDataSetChanged();
				//
				if (index == 0) {
					setNavTitle("我关注的医生");
					mStartUid = null;
					mPos = 0;
					// text_empty.setText("您还没有关注的医生");
				} else if (index == 1) {
					// text_empty.setText("还没有关注您的医生");
					setNavTitle("关注我的医生");
					mStartUid = null;
					mPos = 1;
				}

				// loadData(false);
				onPullDownToRefresh(null);
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		// MobclickAgent.onResume(this);
		onPullDownToRefresh(null);
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

		mStartUid = null;
		array.clear();
		loadData(true);
	}

	@Override
	public void onPullUpToLoadMore(PullToRefreshBase<ListView> refreshView) {
		loadData(false);
	}

	/**
	 * method desc：
	 */
	public void loadData(boolean isShowDialog) {
		if (mPos == 0) {
			FollowGetListTask task = new FollowGetListTask();
			FollowGetListRequest req = new FollowGetListRequest();
			req.token = GlobalSettings.sToken;
			req.targetType = targetType;
			req.type = 1;

			req.uid = GlobalSettings.sUid;
			task.setRequest(req);
			task.addListener(new NetTaskListener<FollowGetListTask.FollowGetListRequest, FollowGetListTask.FollowGetListResponse>() {

				@Override
				public void onException(
						INetTask<FollowGetListRequest, FollowGetListResponse> task,
						Exception e) {
					// Toast.makeText(MyFollowingDoctorActivity.this,
					// e.getMessage(), Toast.LENGTH_SHORT).show();
				}

				@Override
				public void onComplete(
						INetTask<FollowGetListRequest, FollowGetListResponse> task,
						FollowGetListResponse response) {
					list_following_doctor.doComplete();
					if (!CommonUtility.isNull(response)
							&& response.ResultCode == 200) {
						ArrayList<Follow> follows = response.Res.Follows;
						if (mShowTitleNumberFollow) {
							mMyFollow.setText(String.format(mFollow,
									follows.size()));
							mShowTitleNumberFollow = false;
						} else {
							getFollows(follows, false);
						}

					} else {
						list_following_doctor.setContextEmptyType(true, 2);
						CommonUtility.toast(getApplicationContext(),
								R.string.server_unavailable);
					}
				}
			});
			add(task);
		} else if (mPos == 1) {
			FollowGetFollowersListTask task = new FollowGetFollowersListTask();
			FollowGetFollowersListRequest req = new FollowGetFollowersListRequest();
			req.following_id = GlobalSettings.sUid;
			req.startuid = mStartUid;
			task.setRequest(req);
			task.addListener(new NetTaskListener<FollowGetFollowersListTask.FollowGetFollowersListRequest, FollowGetFollowersListTask.FollowGetFollowersListResponse>() {
				@Override
				public void onComplete(
						INetTask<FollowGetFollowersListRequest, FollowGetFollowersListResponse> task,
						FollowGetFollowersListResponse response) {
					list_following_doctor.doComplete();
					if (!CommonUtility.isNull(response)
							&& response.ResultCode == 200) {
						ArrayList<Follow> follows = response.Res.Follows;
						if (mShowTitleNumberFollowed) {
							mFollowMe.setText(String.format(mFollowed,
									follows.size()));
							mShowTitleNumberFollowed = false;
						} else {
							getFollows(follows, true);
						}
					} else if (response.ResultCode == -1001) {
						mFollowMe.setText(String.format(mFollowed, 0));
					} else {
						CommonUtility.toast(getApplicationContext(),
								R.string.server_unavailable);
					}

				}

				@Override
				public void onException(
						INetTask<FollowGetFollowersListRequest, FollowGetFollowersListResponse> task,
						Exception e) {
					list_following_doctor.setContextEmptyType(true, 2);
					// Toast.makeText(MyFollowingDoctorActivity.this,
					// e.getMessage(), Toast.LENGTH_SHORT).show();
				}
			});
			req.type = 1;
			add(task);
		} else if (mPos == 2) {
			RelationshipGetListTask task = new RelationshipGetListTask();
			req.startrsuid = mStartUid;
			req.token = GlobalSettings.sToken;
			task.setRequest(req);
			task.addListener(new NetTaskListener<RelationshipGetListTask.RelationshipGetListRequest, RelationshipGetListTask.RelationshipGetListResponse>() {

				@Override
				public void onComplete(
						INetTask<RelationshipGetListRequest, RelationshipGetListResponse> task,
						RelationshipGetListResponse response) {
					list_following_doctor.doComplete();
					if (!CommonUtility.isNull(response)
							&& response.ResultCode == 200) {
						ArrayList<UserWrapper> users = response.Res.Users;

						for (UserWrapper user : users) {
							if (user.User != null) {
								boolean has = false;
								for (UserWrapper u : Users) {
									if (u.Uid == user.Uid) {
										has = true;
										break;
									}
								}
								if (!has) {
									Users.add(user);
								}
							}
						}
						if (Users.size() > 1) {
							mStartUid = Users.get(Users.size() - 1).Uid;
						}

						mMyAdapter.setDataProvider(Users);
						mMyAdapter.notifyDataSetChanged();
						// list_following_doctor.setHasMoreData(false);
						if (Users.size() < 1) {
							list_following_doctor.setContextEmptyType(true, 1);
						} else {
							list_following_doctor.setContextEmptyType(false, 1);
						}
					} else {
						list_following_doctor.setContextEmptyType(true, 2);
						CommonUtility.toast(getApplicationContext(),
								R.string.server_unavailable);
					}
				}

				@Override
				public void onException(
						INetTask<RelationshipGetListRequest, RelationshipGetListResponse> task,
						Exception e) {
					Toast.makeText(MyFollowingDoctorActivity.this,
							e.getMessage(), Toast.LENGTH_SHORT).show();
				}
			});
			add(task);
		}

	}

	private void getFollows(ArrayList<Follow> follows, boolean uid) {
		final ArrayList<Long> uids = new ArrayList<Long>();
		for (int i = 0; i < follows.size(); i++) {
			Follow follow = follows.get(i);
			if (uid) {
				uids.add(follow.Follower_Uid);
			} else {
				uids.add(follow.Following_Id);
			}
			if (i == follows.size() - 1) {
				mStartUid = follow.Following_Id;
			}
		}
		UserGetTask utask = new UserGetTask();
		UserGetRequest ureq = new UserGetRequest();
		ureq.uids = uids;
		utask.setRequest(ureq);

		utask.addListener(new NetTaskListener<UserGetTask.UserGetRequest, UserGetTask.UserGetResponse>() {

			@Override
			public void onComplete(
					INetTask<UserGetRequest, UserGetResponse> task,
					UserGetResponse response) {
				list_following_doctor.doComplete();
				if (!CommonUtility.isNull(response)
						&& response.ResultCode == 200) {

					ArrayList<User> users = response.Res;
					ArrayList<UserWrapper> User = new ArrayList<UserWrapper>();
					for (User u : users) {
						UserWrapper wrapper = new UserWrapper();
						wrapper.User = u;
						wrapper.Uid = u.Uid;
						User.add(wrapper);
					}
					mMyAdapter.setDataProvider(User);
					mMyAdapter.notifyDataSetChanged();
					if (User.size() < 1) {
						list_following_doctor.setContextEmptyType(true, 1);
					} else {
						list_following_doctor.setContextEmptyType(false, 1);
					}

				} else {
					list_following_doctor.setContextEmptyType(true, 1);
					/*
					 * if (uids.size() < 1) {
					 * text_empty.setVisibility(View.VISIBLE); } else {
					 * list_following_doctor.setHasMoreData(false); } if
					 * (mMyAdapter != null) mMyAdapter.notifyDataSetChanged();
					 * list_following_doctor.doComplete();
					 */
				}
			}

			@Override
			public void onException(
					INetTask<UserGetRequest, UserGetResponse> task, Exception e) {

			}
		});
		add(utask);
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int arg2,
			long arg3) {
		try {
			JSONObject object = (JSONObject) view.getTag();
			if (mMyFollowDoctor) {
				object.put("Is_Follow", 1);
				Intent intent = new Intent(activity, DoctorDetailActivity.class);
				intent.putExtra(Constant.IDENTITY_KEY, object.toString());
				intent.putExtra(Constant.IDENTITY_KEY_1,
						Constant.IDENTITY_KEY_1);
				startActivity(intent);
			} else {
				/*
				 * object.put("Is_Follow", 1); Intent intent = new
				 * Intent(activity, PersonHomeActivity.class); //
				 * intent.putExtra(Constant.IDENTITY_KEY, object.toString());
				 * UserExtra extra = new UserExtra();
				 * extra.setUser(JsonUtil.convertFromObject(object,
				 * User.class)); // intent.putExtra(Constant.IDENTITY_KEY_1,
				 * true); extra.putTo(intent); startActivity(intent);
				 */
				UserWrapper user = mMyAdapter.getDataProvider().get(arg2);
				Intent intent = new Intent(getContext(),
						DoctorDetailActivity.class);
				try {
					intent.putExtra(Constant.IDENTITY_KEY,
							JsonUtil.convert(user));
					getContext().startActivity(intent);
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onClick(View view) {
		super.onClick(view);
		int id = view.getId();
		if (id == R.id.text_right) {
			Intent intent = new Intent(activity, SearchActivity.class);
			intent.putExtra(Constant.IDENTITY_KEY_1, mMyFollowDoctor);
			startActivity(intent);
		}
	}

	/*
	 * @Override public void onPause() { super.onPause();
	 * MobclickAgent.onPause(getContext()); }
	 */

}
